package cup.com.icss.utils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Reader;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.net.URLDecoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.sql.Timestamp;
import java.text.BreakIterator;
import java.text.DateFormat;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.UUID;
import java.util.Map.Entry;
import java.util.Random;
import java.util.StringTokenizer;
import java.util.Vector;
import java.util.regex.Pattern;
import java.text.SimpleDateFormat;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;



public class StringUtil {

	public static Pattern p = Pattern.compile("");
	
	/**
	 * StringUtil constructor comment.
	 */
	public StringUtil() {
		super();
	}
	
	/**
	 * 解码得到JSONObject（UTF-8编码）
	 * @param paramsJson
	 * @return
	 * @throws JSONException
	 * @throws UnsupportedEncodingException
	 */
	public static JSONObject DecodeParamsJson(String paramsJson) throws UnsupportedEncodingException, JSONException
	{
		return new JSONObject(URLDecoder.decode(paramsJson,"UTF-8"));
	}
	
	/**
     * 解码得到JSONArray（UTF-8编码）
     * @param paramsJson
     * @return
     * @throws JSONException
     * @throws UnsupportedEncodingException
     */
    public static JSONArray DecodeParamsJsonArr(String paramsJson) throws UnsupportedEncodingException, JSONException
    {
        return new JSONArray(URLDecoder.decode(paramsJson,"UTF-8"));
    }
    
    /**
	 * 
	 * @param str
	 * @param pattern
	 * @return
	 */
	public static Timestamp str2timestamp(String str, String pattern) {
        Timestamp time = null;
        if (!"".equals(str) && str != null) {
            try {
                SimpleDateFormat format = new SimpleDateFormat(pattern);
                Date date = format.parse(str);
                time = new Timestamp(date.getTime());
            } catch (ParseException pe) {
                System.out.println("转换字符串出现异常:" + pe.getMessage());
                pe.printStackTrace();
            }
        }
        return time;
    }
	 
	 /**
	 * 
	 * @param str
	 * @param pattern    格式类型,yyyy-MM-dd 
	 * @return
	 */
	 public static Date str2Date(String str) throws Exception {
	     DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
	     Date date = dateFormat.parse(str);
	     date = java.sql.Date.valueOf(str);
	     return date;
	 }
	 
	 public static Calendar str2Calendar(String str, String pattern) throws Exception {
	     SimpleDateFormat sdf= new SimpleDateFormat(pattern);
	     Date date =sdf.parse(str);
	     Calendar calendar = Calendar.getInstance();
	     calendar.setTime(date);
	     return calendar;
	 }
	 
	 public static Calendar date2Calendar(Date date) throws Exception {
	     Calendar calendar = Calendar.getInstance();
	     calendar.setTime(date);
	     return calendar;
	 }
	 
	 
	/**
	 * 转义数据库通配字符：'%','_'
	 * Creation date: (2000-12-20 14:49:55)
	 * @return java.lang.String
	 * @param src java.lang.String
	 */
	public static String convertCastChar(String src) {
		if (src == null || src.equals("")) {
			return src;
		}
		int			 length = src.length();
		StringBuffer tmp = new StringBuffer();
		for (int i = 0; i < length; i++) {
			switch (src.charAt(i)) {
				case '%':
				case '_':
				case '\\':
					tmp.append("\\");
					break;
			}
			tmp.append(src.charAt(i));
		}
		return tmp.toString();
	}

	/**
	 * 转换常见的Html符号
	 * Creation date: (2000-12-20 14:58:19)
	 * @return java.lang.String
	 * @param src java.lang.String
	 */
	public static String convertForHtml(String src) {
		if (src == null || src.equals("")) {
			return src;
		}
		int			 length = src.length();
		StringBuffer tmp = new StringBuffer();
		for (int i = 0; i < length; i++) {
			switch (src.charAt(i)) {
				case '<':
					tmp.append("&lt;");
					break;
				case '>':
					tmp.append("&gt;");
					break;
				case '"':
					tmp.append("&quot;");
					break;
				case ' ': {
						int spaceCount = 0;
						for (; src.charAt(i) == ' '; i++, spaceCount++){};
						for (int j = 0; j < spaceCount / 2; j++) {
							tmp.append("　");
						}
						if (spaceCount % 2 != 0) {
							tmp.append("&#160;");
						}
						--i;
						break;
					}
				case '\n':
					tmp.append("<br/>");
					break;
				case '&':
					tmp.append("&amp;");
					break;
				case '\r':
					break;
				default:
					tmp.append(src.charAt(i));
					break;
			}
		}
		return tmp.toString();
	}

	/**
	 * Insert the method's description here.
	 * Creation date: (2001-6-6 8:43:25)
	 * @return java.lang.String
	 * @param srv java.lang.String
	 */
	public static String convertForXml(String src) {
		if (src == null || src.equals("")) {
			return src;
		}
		int			 length = src.length();
		StringBuffer tmp = new StringBuffer();
		for (int i = 0; i < length; i++) {
			switch (src.charAt(i)) {
				case '<':
					tmp.append("&lt;");
					break;
				case '>':
					tmp.append("&gt;");
					break;
				case '"':
					tmp.append("&quot;");
					break;
				case ' ': {
						int spaceCount = 0;
						for (; src.charAt(i) == ' '; i++, spaceCount++){};
						for (int j = 0; j < spaceCount / 2; j++) {
							tmp.append("　");
						}
						if (spaceCount % 2 != 0) {
							tmp.append("&#160;");
						}
						--i;
						break;
					}
				case '&':
					tmp.append("&amp;");
					break;
				case '\r':
					break;
				default:
					tmp.append(src.charAt(i));
					break;
			}
		}
		return tmp.toString();
	}

	/**
	 * Insert the method's description here.
	 * Creation date: (2001-6-6 8:43:25)
	 * @return java.lang.String
	 * @param srv java.lang.String
	 */
	public static String convertForXml2(String src) {
		if (src == null || src.equals("")) {
			return src;
		}
		int			 length = src.length();
		StringBuffer tmp = new StringBuffer();
		for (int i = 0; i < length; i++) {
			switch (src.charAt(i)) {
				case ' ': {
						int spaceCount = 0;
						for (; i < src.length() && src.charAt(i) == ' '; i++, spaceCount++){};
						for (int j = 0; j < spaceCount / 2; j++) {
							tmp.append("　");
						}
						if (spaceCount % 2 != 0) {
							tmp.append(" ");
						}
						--i;
						break;
					}
				default:
					tmp.append(src.charAt(i));
					break;
			}
		}
		return tmp.toString();
	}

	/**
	 * 转义单引号
	 * Creation date: (2000-12-20 14:43:29)
	 * @return java.lang.String
	 * @param src java.lang.String
	 */
	public static String convertSingleQuot(String src) {
		if (src == null || src.equals("")) {
			return src;
		}
		int			 length = src.length();
		StringBuffer tmp = new StringBuffer();
		for (int i = 0; i < length; i++) {
			if (src.charAt(i) == '\'') {
				tmp.append("\'\'");
			}
			else {
				tmp.append(src.charAt(i));
			}
		}
		return tmp.toString();
	}

	/**
	 * 子串替换
	 * Creation date: (2000-12-23 15:32:25)
	 * @return java.lang.String
	 * @param src 原字符串
	 * @param mod 需要被替换的字符串
	 * @param str 替换的字符串
	 */
	public static String replace(String src, String mod, String str) {
		if (src == null || src.length() == 0) {
			return src;
		}
		if (mod == null || mod.length() == 0) {
			return src;
		}
		if (src == null) {
			src = "";
		}
		StringBuffer buffer = new StringBuffer();
		int			 idx1 = 0;
		int			 idx2 = 0;
		while ((idx2 = src.indexOf(mod, idx1)) != -1) {
			buffer.append(src.substring(idx1, idx2)).append(str);
			idx1 = idx2 + mod.length();
		}
		buffer.append(src.substring(idx1));
		return buffer.toString();
	}

	/**
	 * Insert the method's description here.
	 * Creation date: (2001-5-30 13:46:08)
	 * @return java.lang.String[]
	 */
	public static String[] split(String src, String delim) {
		if (src == null || delim == null) {
			return null;
		}
		StringTokenizer st = new StringTokenizer(src, delim);
		Vector			vct = new Vector();
		while (st.hasMoreTokens()) {
			vct.add(st.nextToken());
		}
		Object[] tks = vct.toArray();
		String   rt[] = new String[vct.size()];
		System.arraycopy(tks, 0, rt, 0, vct.size());
		return rt;
	}

	/**
	 * velocity 获取数组中某一个位置的元素
	 * @param objects
	 * @param i
	 * @return
	 */
	public static Object getValue(Object[] objects,int i) {
		
		if(objects.length < i) {
			return EMPTY_STRING;
		}
		
		return objects[i-1];
	}
	
	/**
	 * Method declaration
	 * @return
	 * @see
	 */
	public static String getCurrentTimeStamp() {
		DateFormat df = DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.LONG, new Locale("zh", "CN"));
		return (df.format(new java.util.Date(System.currentTimeMillis())));
	}

	public static final String replaceIgnoreCase(String line, String oldString, String newString)
	{
		if(line == null){
			return null;
		}
		String lcLine = line.toLowerCase();
		String lcOldString = oldString.toLowerCase();
		int i = 0;
		if((i = lcLine.indexOf(lcOldString, i)) >= 0)
		{
			char line2[] = line.toCharArray();
			char newString2[] = newString.toCharArray();
			int oLength = oldString.length();
			StringBuffer buf = new StringBuffer(line2.length);
			buf.append(line2, 0, i).append(newString2);
			i += oLength;
			int j;
			for(j = i; (i = lcLine.indexOf(lcOldString, i)) > 0; j = i)
			{
				buf.append(line2, j, i - j).append(newString2);
				i += oLength;
			}

			buf.append(line2, j, line2.length - j);
			return buf.toString();
		} else
		{
			return line;
		}
	}

	public static final String replaceIgnoreCase(String line, String oldString, String newString, int count[])
	{
		if(line == null){
			return null;
		}
		String lcLine = line.toLowerCase();
		String lcOldString = oldString.toLowerCase();
		int i = 0;
		if((i = lcLine.indexOf(lcOldString, i)) >= 0)
		{
			int counter = 0;
			char line2[] = line.toCharArray();
			char newString2[] = newString.toCharArray();
			int oLength = oldString.length();
			StringBuffer buf = new StringBuffer(line2.length);
			buf.append(line2, 0, i).append(newString2);
			i += oLength;
			int j;
			for(j = i; (i = lcLine.indexOf(lcOldString, i)) > 0; j = i)
			{
				counter++;
				buf.append(line2, j, i - j).append(newString2);
				i += oLength;
			}

			buf.append(line2, j, line2.length - j);
			count[0] = counter;
			return buf.toString();
		} else
		{
			return line;
		}
	}

	public static final String replace(String line, String oldString, String newString, int count[])
	{
		if(line == null){
			return null;
		}
		int i = 0;
		if((i = line.indexOf(oldString, i)) >= 0)
		{
			int counter = 0;
			counter++;
			char line2[] = line.toCharArray();
			char newString2[] = newString.toCharArray();
			int oLength = oldString.length();
			StringBuffer buf = new StringBuffer(line2.length);
			buf.append(line2, 0, i).append(newString2);
			i += oLength;
			int j;
			for(j = i; (i = line.indexOf(oldString, i)) > 0; j = i)
			{
				counter++;
				buf.append(line2, j, i - j).append(newString2);
				i += oLength;
			}

			buf.append(line2, j, line2.length - j);
			count[0] = counter;
			return buf.toString();
		} else
		{
			return line;
		}
	}

	public static final String escapeHTMLTags(String in)
	{
		if(in == null){
			return null;
		}
		int i = 0;
		int last = 0;
		char input[] = in.toCharArray();
		int len = input.length;
		StringBuffer out = new StringBuffer((int)((double)len * 1.3D));
		for(; i < len; i++)
		{
			char ch = input[i];
			if(ch <= '>'){
				if(ch == '<')
				{
					if(i > last){
						out.append(input, last, i - last);
					}
					last = i + 1;
					out.append(LT_ENCODE);
				} else{
					if(ch == '>')
					{
						if(i > last){
							out.append(input, last, i - last);
						}
						last = i + 1;
						out.append(GT_ENCODE);
					}
				}
			}
		}

		if(last == 0){
			return in;
		}
		if(i > last){
			out.append(input, last, i - last);
		}
		return out.toString();
	}

	public static final String escapeNull(String str) {
		return (str == null || str.trim().length() == 0) ? "&nbsp;" : str;
	}
	public static final String escapeNull(java.sql.Date str) {
		return str == null ? "&nbsp;" : DateFormat.getDateInstance(DateFormat.DEFAULT, Locale.CHINA).format(str);
	}
	public static final String escapeNull(java.util.Date str) {
		return str == null ? "&nbsp;" : DateFormat.getDateInstance(DateFormat.DEFAULT, Locale.CHINA).format(str);
	}
	public static final String escapeNull(java.sql.Timestamp str) {
		return str == null ? "&nbsp;" : DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT, Locale.CHINA).format(str);
	}
	public static final String escapeEmpty(String str) {
		return (str == null || str.length() == 0) ? " " : str;
	}
	
	public static final synchronized String hash(String data)
	{
		if(digest == null){
			try{
				digest = MessageDigest.getInstance("MD5");
			}catch(NoSuchAlgorithmException nsae){
				nsae.printStackTrace();
			}
		}
		digest.update(data.getBytes());
		return encodeHex(digest.digest());
	}

	public static final String encodeHex(byte bytes[])
	{
		StringBuffer buf = new StringBuffer(bytes.length * 2);
		for(int i = 0; i < bytes.length; i++)
		{
			if((bytes[i] & 0xff) < 16){
				buf.append("0");
			}
			buf.append(Long.toString(bytes[i] & 0xff, 16));
		}

		return buf.toString();
	}
	public static final String getWeekByHex(int week){
		switch(week)
		{
		case 1:
			return "星期日";
		case 2:
			return "星期一";
		case 3:
			return "星期二";
		case 4:
			return "星期三";
		case 5:
			return "星期四";
		case 6:
			return "星期五";
		case 7:
			return "星期一";
			default:
				return null;
		}
	}
	public static final byte[] decodeHex(String hex)
	{
		char chars[] = hex.toCharArray();
		byte bytes[] = new byte[chars.length / 2];
		int byteCount = 0;
		for(int i = 0; i < chars.length; i += 2)
		{
			byte newByte = 0;
			newByte |= hexCharToByte(chars[i]);
			newByte <<= 4;
			newByte |= hexCharToByte(chars[i + 1]);
			bytes[byteCount] = newByte;
			byteCount++;
		}

		return bytes;
	}

	private static final byte hexCharToByte(char ch)
	{
		switch(ch)
		{
			case 48: // '0'
				return 0;

			case 49: // '1'
				return 1;

			case 50: // '2'
				return 2;

			case 51: // '3'
				return 3;

			case 52: // '4'
				return 4;

			case 53: // '5'
				return 5;

			case 54: // '6'
				return 6;

			case 55: // '7'
				return 7;

			case 56: // '8'
				return 8;

			case 57: // '9'
				return 9;

			case 97: // 'a'
				return 10;

			case 98: // 'b'
				return 11;

			case 99: // 'c'
				return 12;

			case 100: // 'd'
				return 13;

			case 101: // 'e'
				return 14;

			case 102: // 'f'
				return 15;

			case 58: // ':'
			case 59: // ';'
			case 60: // '<'
			case 61: // '='
			case 62: // '>'
			case 63: // '?'
			case 64: // '@'
			case 65: // 'A'
			case 66: // 'B'
			case 67: // 'C'
			case 68: // 'D'
			case 69: // 'E'
			case 70: // 'F'
			case 71: // 'G'
			case 72: // 'H'
			case 73: // 'I'
			case 74: // 'J'
			case 75: // 'K'
			case 76: // 'L'
			case 77: // 'M'
			case 78: // 'N'
			case 79: // 'O'
			case 80: // 'P'
			case 81: // 'Q'
			case 82: // 'R'
			case 83: // 'S'
			case 84: // 'T'
			case 85: // 'U'
			case 86: // 'V'
			case 87: // 'W'
			case 88: // 'X'
			case 89: // 'Y'
			case 90: // 'Z'
			case 91: // '['
			case 92: // '\\'
			case 93: // ']'
			case 94: // '^'
			case 95: // '_'
			case 96: // '`'
			default:
				return 0;
		}
	}

	public static String encodeBase64(String data)
	{
		return encodeBase64(data.getBytes());
	}

	public static String encodeBase64(byte data[])
	{
		int len = data.length;
		StringBuffer ret = new StringBuffer((len / 3 + 1) * 4);
		for(int i = 0; i < len; i++)
		{
			int c = data[i] >> 2 & 0x3f;
			ret.append("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(c));
			c = data[i] << 4 & 0x3f;
			if(++i < len){
				c |= data[i] >> 4 & 0xf;
			}
			ret.append("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(c));
			if(i < len)
			{
				c = data[i] << 2 & 0x3f;
				if(++i < len){
					c |= data[i] >> 6 & 3;
				}
				ret.append("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(c));
			} else
			{
				i++;
				ret.append('=');
			}
			if(i < len)
			{
				c = data[i] & 0x3f;
				ret.append("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(c));
			} else
			{
				ret.append('=');
			}
		}

		return ret.toString();
	}

	public static String decodeBase64(String data)
	{
		return decodeBase64(data.getBytes());
	}

	public static String decodeBase64(byte data[])
	{
		int len = data.length;
		StringBuffer ret = new StringBuffer((len * 3) / 4);
		for(int i = 0; i < len; i++)
		{
			int c = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".indexOf(data[i]);
			i++;
			int c1 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".indexOf(data[i]);
			c = c << 2 | c1 >> 4 & 3;
			ret.append((char)c);
			if(++i < len)
			{
				c = data[i];
				if(61 == c){
					break;
				}
				c = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".indexOf((char)c);
				c1 = c1 << 4 & 0xf0 | c >> 2 & 0xf;
				ret.append((char)c1);
			}
			if(++i >= len){
				continue;
			}
			c1 = data[i];
			if(61 == c1){
				break;
			}
			c1 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".indexOf((char)c1);
			c = c << 6 & 0xc0 | c1;
			ret.append((char)c);
		}

		return ret.toString();
	}

	public static final String[] toLowerCaseWordArray(String text)
	{
		if(text == null || text.length() == 0){
			return new String[0];
		}
		ArrayList wordList = new ArrayList();
		BreakIterator boundary = BreakIterator.getWordInstance();
		boundary.setText(text);
		int start = 0;
		for(int end = boundary.next(); end != -1; end = boundary.next())
		{
			String tmp = text.substring(start, end).trim();
			tmp = replace(tmp, "+", "");
			tmp = replace(tmp, "/", "");
			tmp = replace(tmp, "\\", "");
			tmp = replace(tmp, "#", "");
			tmp = replace(tmp, "*", "");
			tmp = replace(tmp, ")", "");
			tmp = replace(tmp, "(", "");
			tmp = replace(tmp, "&", "");
			if(tmp.length() > 0){
				wordList.add(tmp);
			}
			start = end;
		}

		return (String[])wordList.toArray(new String[wordList.size()]);
	}

	public static final String randomString(int length)
	{
		if(length < 1){
			return null;
		}
		char randBuffer[] = new char[length];
		for(int i = 0; i < randBuffer.length; i++){
			randBuffer[i] = numbersAndLetters[randGen.nextInt(71)];
		}
		return new String(randBuffer);
	}

	public static final String chopAtWord(String string, int length)
	{
		if(string == null){
			return string;
		}
		char charArray[] = string.toCharArray();
		int sLength = string.length();
		if(length < sLength){
			sLength = length;
		}
		for(int i = 0; i < sLength - 1; i++)
		{
			if(charArray[i] == '\r' && charArray[i + 1] == '\n'){
				return string.substring(0, i + 1);
			}
			if(charArray[i] == '\n'){
				return string.substring(0, i);
			}
		}

		if(charArray[sLength - 1] == '\n'){
			return string.substring(0, sLength - 1);
		}
		if(string.length() < length){
			return string;
		}
		for(int i = length - 1; i > 0; i--){
			if(charArray[i] == ' '){
				return string.substring(0, i).trim();
			}
		}

		return string.substring(0, length);
	}


	public static final String escapeForXML(String string)
	{
		if(string == null){
			return null;
		}
		int i = 0;
		int last = 0;
		char input[] = string.toCharArray();
		int len = input.length;
		StringBuffer out = new StringBuffer((int)((double)len * 1.3D));
		for(; i < len; i++)
		{
			char ch = input[i];
			if(ch <= '>'){
				if(ch == '<')
				{
					if(i > last){
						out.append(input, last, i - last);
					}
					last = i + 1;
					out.append(LT_ENCODE);
				} else{
					if(ch == '&')
					{
						if(i > last){
							out.append(input, last, i - last);
						}
						last = i + 1;
						out.append(AMP_ENCODE);
					} else{
						if(ch == '"')
						{
							if(i > last){
								out.append(input, last, i - last);
							}
							last = i + 1;
							out.append(QUOTE_ENCODE);
						}
					}
				}
			}
		}

		if(last == 0){
			return string;
		}
		if(i > last){
			out.append(input, last, i - last);
		}
		return out.toString();
	}

	public static final String unescapeFromXML(String string)
	{
		string = replace(string, "&lt;", "<");
		string = replace(string, "&gt;", ">");
		string = replace(string, "&quot;", "\"");
		return replace(string, "&amp;", "&");
	}

	public static final String zeroPadString(String string, int length)
	{
		if(string == null || string.length() > length)
		{
			return string;
		} else
		{
			StringBuffer buf = new StringBuffer(length);
			buf.append(zeroArray, 0, length - string.length()).append(string);
			return buf.toString();
		}
	}

	public static final String dateToMillis(Date date)
	{
		return zeroPadString(Long.toString(date.getTime()), 15);
	}

	/**
	 * 格式化以下划线'_'或减号'-'隔开的字符串，如：
	 * "user-name", 可以格式化为"userName"
	 * @return java.lang.String
	 * @param name java.lang.String
	 * @param firstCharUpperCase boolean 如果为true，那么返回的首字母大写，反之，小写
	 */
	public static final String formatJavaName(String name,boolean firstCharUpperCase){
		if (name == null || name.length() <= 1) {
			return name;
		}
		StringTokenizer tokenizer = new StringTokenizer(name,"-_");
		StringBuffer tmp = new StringBuffer();
		while (tokenizer.hasMoreTokens()){
			String token = tokenizer.nextToken();
			tmp.append(Character.toUpperCase(token.charAt(0))).append(token.substring(1));
		}
		if (!firstCharUpperCase){
			String ch = String.valueOf(Character.toLowerCase(tmp.charAt(0)));
			tmp.replace(0,1,ch);
		}
		return tmp.toString();
	}

	public static final String getGetMethodName(String name){
		return "get"+formatJavaName(name,true);
	}
	public static final String getSetMethodName(String name){
		return "set"+formatJavaName(name,true);
	}

	/**
	 * 格式化以下划线'_'或减号'-'隔开的字符串，首字母小写，如：
	 * "user-name", 可以格式化为"userName"
	 * @return java.lang.String
	 * @param name java.lang.String
	 */
	public static final String formatJavaName(String name){
		return formatJavaName(name,false);
	}

	/**
	 * @param input
	 * @return @throws
	 *         IOException
	 */
	public static String reader2str(Reader input) throws IOException {
		return reader2str(input, 4096);
	}

	/**
	 * @param input
	 * @param bufferSize
	 * @return @throws
	 *         IOException
	 */
	public static String reader2str(Reader input, int bufferSize) throws IOException {
		StringWriter sw = new StringWriter();
		copyReader(input, sw, bufferSize);
		return sw.toString();
	}

	/**
	 * @param input
	 * @param output
	 * @param bufferSize
	 * @throws IOException
	 */
	public static void copyReader(Reader input, Writer output, int bufferSize) throws IOException {
		char buffer[] = new char[bufferSize];
		for (int n = 0; -1 != (n = input.read(buffer));){
			output.write(buffer, 0, n);
		}
	}
	
	/*public static String formatCarriage2Html(String str) throws RESyntaxException {
		return formatCarriage2Html(str, "<br>");
	}

	public static String formatCarriage2Html(String str, String replacement) throws RESyntaxException {
		RE r = new RE("\r\n", RE.REPLACE_ALL);
		return r.subst(str, replacement);
	}
	
	public static String formatSpace2Sql(String str) throws RESyntaxException {
		RE r = new RE(" ", RE.REPLACE_ALL);
		return r.subst(str, "%");
	}*/
	
	/*
	public static String list2String(List list) {
		if (list == null) {
			return StringUtil.EMPTY_STRING;
		}			
		int len = list.size();
		if (len == 0) {
			return StringUtil.EMPTY_STRING;
		}
		StringBuffer buf = new StringBuffer();
		for ( int i=0; i<len-1; i++ ) {
			buf.append(StringUtil.SINGLE_QUOTE).append( list.get(i) ).append(StringUtil.QUOTE_COMMA);
		}
		return buf.append(StringUtil.SINGLE_QUOTE).append( list.get(len-1) ).append(StringUtil.SINGLE_QUOTE).toString();
	}
	*/
	
    public static String numberToString(Number nu) {
    	if(null == nu) {
    		return "0";
    	}
    	return nu.toString();
    }
    
    public static String toString(String nu) {
    	if(null == nu) {
    		return EMPTY_STRING;
    	}
    	return nu.toString();
    }
    
    /**
     * 
     * @Title: list2SQLString
     * @Description: 将数组里的值转换成sql能用的字符串，
     * 				 例如：{"a","b","c"}转换成"('a','b','c')"
     * @param str
     * @return
     */
    public static String list2SQLString(List strList) {
    	StringBuffer buffer = new StringBuffer();
    	buffer.append("(");
    	if(isEmpty(strList)) {
    	    buffer.append("''");
    	} else {
        	for (int i = 0; i < strList.size(); i++) {
        		if(i+1 == strList.size()) {
        			buffer.append("'").append(strList.get(i)).append("'");
        		} else {
        			buffer.append("'").append(strList.get(i)).append("',");
        		}
    		}
        	
    	}
    	buffer.append(") ");
    	return buffer.toString();
    }
    
    /**
     * 
     * @Title: array2SQLString
     * @Description: 将数组里的值转换成sql能用的字符串，
     * 				 例如：{"a","b","c"}转换成"('a','b','c')"
     * @param str
     * @return
     */
    public static String array2SQLString(String[] str) {
    	StringBuffer buffer = new StringBuffer();
    	buffer.append("(");
    	for (int i = 0; i < str.length; i++) {
    		if(i+1 == str.length) {
    			buffer.append("'").append(str[i]).append("'");
    		} else {
    			buffer.append("'").append(str[i]).append("',");
    		}
		}
    	buffer.append(") ");
    	return buffer.toString();
    }
    
    /**
     * @Title: array2SQLLong
     * @Description: 将数组里的值转换成sql能用的字符串，
     * 				 例如：{a,b,c}转换成"(a,b,c)"
     * @param str
     * @return
     */
    public static String array2SQLLong(String[] str) {
    	StringBuffer buffer = new StringBuffer();
    	buffer.append("(");
    	for (int i = 0; i < str.length; i++) {
    		if(i+1 == str.length) {
    			buffer.append(str[i]);
    		} else {
    			buffer.append(str[i]).append(",");
    		}
		}
    	buffer.append(")");
    	return buffer.toString();
    }
    
    /**
     * 
     * @Title: array2SString
     * @Description: 将数组里的值转换成字符串，用英文逗号分开
     *               例如：{"a","b","c"}转换成"a,b,c"
     * @param str
     * @return
     */
    public static String array2String(String[] str) {
        StringBuffer buffer = new StringBuffer();
        for (int i = 0; i < str.length; i++) {
            if(i+1 == str.length) {
                buffer.append(str[i]);
            } else {
                buffer.append(str[i]).append(",");
            }
        }
        return buffer.toString();
    }
    
    /**
     * 
     * @Title: list2SString
     * @Description: 将List里的值转换成字符串，用英文逗号分开
     *               例如：{"a","b","c"}转换成"a,b,c"
     * @param str
     * @return
     */
    public static String list2String(List<String> strList) {
        StringBuffer buffer = new StringBuffer();
        for (int i = 0; i < strList.size(); i++) {
            if(i+1 == strList.size()) {
                buffer.append(strList.get(i));
            } else {
                buffer.append(strList.get(i)).append(",");
            }
        }
        return buffer.toString();
    }
    
    public static boolean isEmpty(String str) {
    	if(str == null || str.equals("") || str.equals("null")) {
    		return true;
    	} else {
    		return false;
    	}
    }
    
    public static boolean isEmpty(List list) {
    	if(list == null) {
    		return true;
    	} else if(list != null && list.size() == 0) {
    		return true;
    	} else {
    		return false;
    	}
    }
    
    public static boolean isEmpty(Object[] obj) {
        if(obj == null) {
            return true;
        } else if(obj != null && obj.length == 0) {
            return true;
        } else {
            return false;
        }
    }
	
    /**
     * 字符串转UTF-8
     * @param s
     * @return
     */
    public static String toUtf8String(String s) {
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < s.length(); i++) {
			char c = s.charAt(i);
			if (c >= 0 && c <= 255) {
				sb.append(c);
			} else {
				byte[] b;
				try {
					b = Character.toString(c).getBytes("utf-8");
				} catch (Exception ex) {
					System.out.println(ex);
					b = new byte[0];
				}
				for (int j = 0; j < b.length; j++) {
					int k = b[j];
					if (k < 0){
						k += 256;
					}
					sb.append('%' + Integer.toHexString(k).toUpperCase());
				}
			}
		}
		return sb.toString();
	}
    
	private static final char QUOTE_ENCODE[] = "&quot;".toCharArray();
	private static final char AMP_ENCODE[] = "&amp;".toCharArray();
	private static final char LT_ENCODE[] = "&lt;".toCharArray();
	private static final char GT_ENCODE[] = "&gt;".toCharArray();
	private static MessageDigest digest = null;
	private static final int fillchar = 61;
	private static final String cvt = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
	private static Random randGen = new Random();
	private static char numbersAndLetters[] = "0123456789abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray();
	private static final char zeroArray[] = "0000000000000000".toCharArray();
	private static final String QUOTE_COMMA="', ";
	private static final String SINGLE_QUOTE="'";
	public static final String EMPTY_STRING="";
	public static final String SPLIT_STRING="＼";

	public static String escapeFromNull(String str) {
		if(null == str || str.trim().length() == 0) {
			return StringUtil.EMPTY_STRING;
		}
		return str;
	}
	
	//modified by 冯康 2012-12-27 for 流程节点排序方式由ID排序改为序号排序 start
	/**
	 * Integer对象比较方法
	 * @param base
	 * @param another
	 * return retVal 0:相等 1:base大于another -1:base小于another
	 */
	public static int compareInteger(Integer base, Integer another)
	{
		int retVal;
		if(base == null && another == null)
		{
			retVal = 0;
		} else if(base == null)
		{
			retVal = -1;
		} else if(another == null)
		{
			retVal = 1;
		} else
		{
			retVal = base.compareTo(another);
		}
		return retVal;
	}
	//modified by 冯康 2012-12-27 end
	
	/**
	 * 公文审批时list装的是map map的key是数据字段名，专门用作公文审批时的方法
	 */
	@SuppressWarnings("unchecked")
	public static List distinctAttachByName(List attchList){
		List list = new ArrayList();
		Map map = new LinkedHashMap(); //保证顺序
		for (Iterator iterator = attchList.iterator(); iterator.hasNext();) {
			Map attachment = (Map) iterator.next();
			map.put(attachment.get("ATTACH_NAME"), attachment);
		}
		Iterator iter = map.entrySet().iterator();  //获得map的Iterator
		while(iter.hasNext()) {		
			Entry entry = (Entry)iter.next();		
			list.add(entry.getValue());		
		}
//		LogUtil.debugLog("########附件排除名称相同的记录,之前附件的个数: "+attchList.size()+",排除后的个数："+list.size());
		return list;
	}
	
	/**
     * 查询时切割字符串
     * @param string
     * @return
     */
    public static String splitString(String title) {
        //Pattern p = Pattern.compile("");
        String[] txt = p.split(title);
        for (int i = 0; i < txt.length; i++) {
            String str = txt[i];
            if("".equals(str)) {
                title = str;
            } else {
                title = title+str+'%';
            }
        }
        return title;
    }
    
    /**
     * 序列化对象，返回字符串
     * @param object
     * @return
     * @throws Exception
     */
    public final static String serialize(Object object) throws Exception {
        ByteArrayOutputStream byteArrayOutputStream = null;
        ObjectOutputStream objectOutputStream = null;
        String serStr = "";
        try {
            byteArrayOutputStream = new ByteArrayOutputStream();  
            objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);  
            objectOutputStream.writeObject(object);    
            serStr = byteArrayOutputStream.toString("ISO-8859-1");  
            serStr = java.net.URLEncoder.encode(serStr, "UTF-8");  
        } catch (Exception e) {
//            LogUtil.errorLog(StringUtil.class, "序列化失败", e);
            throw e;
        } finally {
            if(objectOutputStream != null) {
                objectOutputStream.close();
            }
            if(byteArrayOutputStream != null) {
                byteArrayOutputStream.close();
            }
        }
          
        return serStr;
    }
    
    /**
     * 反序列化对象
     * @param serStr
     * @return
     * @throws Exception
     */
    public final static Object deserialize(String serStr) throws Exception {
        String redStr = "";
        Object object = null;
        ByteArrayInputStream byteArrayInputStream = null;
        ObjectInputStream objectInputStream = null;
        try {
            redStr = java.net.URLDecoder.decode(serStr, "UTF-8");  
            byteArrayInputStream = new ByteArrayInputStream(redStr.getBytes("ISO-8859-1"));  
            objectInputStream = new ObjectInputStream(byteArrayInputStream);   
            object = objectInputStream.readObject();   
            
        } catch (Exception e) {
//            LogUtil.errorLog(StringUtil.class, "反序列化失败", e);
            throw e;
        } finally {
            if(objectInputStream != null) {
                objectInputStream.close();
            }
            if(byteArrayInputStream != null) {
                byteArrayInputStream.close();
            }
        }
        return object;
    }
    
    /**
     * 姓名带“*”的返回true
     * @param str
     * @return
     * @throws Exception
     */
    public static boolean containAsterisk(String str) {
        try {
            if(!isEmpty(str)) {
                if(str.indexOf("**") > -1) {
                    return false;
                } else if(str.indexOf("*") > -1) {
                    return true;
                }
            }
        } catch (Exception e) {
//            LogUtil.errorLog(StringUtil.class, "containAsterisk", e);
        }
        return false;
    }
    
    
    
    /**
     * md5加密
     */
	public static String md5(String inputText) {
		return encrypt(inputText, "md5");
	}
	
	public static String encrypt(String inputText, String algorithmName) {
		if (inputText == null || "".equals(inputText.trim())) {
			throw new IllegalArgumentException("请输入要加密的内容");
		}
		if (algorithmName == null || "".equals(algorithmName.trim())) {
			algorithmName = "md5";
		}
		String encryptText = null;
		try {
			MessageDigest m = MessageDigest.getInstance(algorithmName);
			m.update(inputText.getBytes("UTF8"));
			byte s[] = m.digest();
			// m.digest(inputText.getBytes("UTF8"));
			return hex(s);
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return encryptText;
	}
	
	// 返回十六进制字符串
	private static String hex(byte[] arr) {
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < arr.length; ++i) {
			sb.append(Integer.toHexString((arr[i] & 0xFF) | 0x100).substring(1,
					3));
		}
		return sb.toString();
	}
	
	/**
     * <p>Checks if a String is whitespace, empty ("") or null.</p>
     *
     * <pre>
     * StringUtils.isBlank(null)      = true
     * StringUtils.isBlank("")        = true
     * StringUtils.isBlank(" ")       = true
     * StringUtils.isBlank("bob")     = false
     * StringUtils.isBlank("  bob  ") = false
     * </pre>
     *
     * @param str  the String to check, may be null
     * @return <code>true</code> if the String is null, empty or whitespace
     * @since 2.0
     */
    public static boolean isBlank(String str) {
        int strLen;
        if (str == null || (strLen = str.length()) == 0) {
            return true;
        }
        for (int i = 0; i < strLen; i++) {
            if ((Character.isWhitespace(str.charAt(i)) == false)) {
                return false;
            }
        }
        return true;
    }
		
	public static void main(String[] args) throws Exception {
	    String str = "中软用户*";
	    System.out.println(containAsterisk(str));
    }
//	public static void main(String[] args) {
//        String src = "filename.doc";
//        String mod = "filename";
//        String str = "111";
//        System.out.println(replace(src, mod, str));
//    }
    /**
     * 生成不带横杠的uuid，带横杠的直接调用UUID.randomUUID()方法
     */
	public static String getUUID(){
		return UUID.randomUUID().toString().replaceAll("-", "");
	}
}
